<?php  
/* OpenBIBLIO -- A library administration web interface
 * Copyright (C) 2002-2005 Frederic Descamps <lefred@tiscali.be>
 * Copyright (C) 2011-2012 Laurent Luyssen   <big.lol13@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

session_start();
include_once("includes/db.inc");
include_once("includes/functions.inc");
include_once "includes/searchDAO.inc";
include_once("includes/session.inc");

if (!isset($_GET['export'])) {
	$title = "<H1>Recherche</H1>";
	include_once ("includes/header.inc");
}
include_once "includes/colCfgDAO.inc";

/**
 *
 * @staticvar array $postVars
 * @param SearchDAO $dao 
 */
function processPostData($dao) {
	static $postVars = array(
		// DB column, post field, search type
		array('nom', 'liv_nom', SearchFilter::TYPE_LIKE),
		array('auteur', 'liv_auteur', SearchFilter::TYPE_LIKE),
		array('ISBN', 'liv_ISBN', SearchFilter::TYPE_LIKE),
		array('edition', 'liv_ed', SearchFilter::TYPE_LIKE),
		array('collection', 'liv_col', SearchFilter::TYPE_LIKE),
		array('location_ID', 'liv_location', SearchFilter::TYPE_EQUAL),
		array('etat_ID', 'liv_etat', SearchFilter::TYPE_EQUAL),
		array('genre_ID', 'liv_genre', SearchFilter::TYPE_EQUAL),
		array('motclefs', 'liv_motclefs', SearchFilter::TYPE_LIKE),
		array('resume', 'liv_resume', SearchFilter::TYPE_LIKE)
	);
	
	foreach ($postVars as $postVar) {
		if (isset($_POST[$postVar[1]])) {
			if ($postVar[0] == 'ISBN')
				$value = return_isbn($_POST[$postVar[1]]);
			else
				$value =  $_POST[$postVar[1]];
			$dao->addFilter ($postVar[0], $value, $postVar[2]);
		}
		else
			$dao->removeFilter ($postVar[0]);
	}
	if (isset($_POST['liv_prete']) && ($_POST['liv_prete'] != '0')) 
		$dao->setIncludeLoaned(TRUE);
	else
		$dao->setIncludeLoaned(FALSE);
		
	if (isset($_POST['liv_pas_prete']) && ($_POST['liv_pas_prete'] != '0')) 
		$dao->setIncludeNotLoaned(TRUE);
	else
		$dao->setIncludeNotLoaned(FALSE);
	
	if (isset($_POST['sort_col']) && !empty($_POST['sort_col'])) 
		$dao->setSortCol($_POST['sort_col']);
}

/**
 *
 * @param SearchDAO $dao 
 */
function exportResults($dao) {
	header("Content-Type: text/csv");
	header("Content-disposition: attachment; filename=openbiblio.csv");
	$rc = $dao->doSearch(FALSE, TRUE, TRUE);
	if ($rc) {
		echo "#id;nom;auteur;isbn;location;edition;date;collection;numero;genre;etat;mots_clefs;resume\n";
		while (($r = $dao->getRow()) !== FALSE) {
			// Replace any occurence of the separator ';' by a ','
			foreach ($r as $key => $value)
				$row[$key] = str_replace(";", ",", $value);
			echo $row['id'].';'.$row['nom'].';'.$row['auteur'].";".$row['ISBN'].';';
			echo get_location_string($row['local'], $row['biblio'], $row['rangee']).";";
			echo $row['edition'].';'.$row['date_ed'].';'.$row['collection'].';';
			echo $row['numero'].';'.$row['genre'].';'.$row['etat'].";";
			echo $row['motclefs'].";".$row['resume']."\n";
			unset($row);
		}
	}
}

$dao = SearchDAO::getInstance();
if (isset($_GET['export'])) {
	exportResults($dao);
	exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
	processPostData($dao);
$sort_col   = $dao->getPrimarySortColumn();
$sort_order = $dao->getPrimarySortOrder();

$genres    = get_genres();
$etats     = get_etats();
$locations = get_locations();
?>

<script type="text/javascript">
function submitform(form_name, column) {
	if (column != '') 
		document.forms[form_name].sort_col.value = column;
	document.forms[form_name].submit();
}

function newPopup(url) {
	popupWindow = window.open(url,'popUpWindow',
'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no');
}

</script>

<br/>
<CENTER>
<form action="search.php" name="search_form" METHOD="POST">
<input type="hidden" name="sort_col" value="">
<TABLE id=tabsearch>
  <TR>
	 <TD colspan=2>
      <?php echo _("Titre"); ?>&nbsp;:
      <INPUT TYPE="text" NAME="liv_nom" size=25" <?php if ($nom = $dao->getFilter('nom')) echo 'value="'.$nom.'"'; ?> >
    </TD>
	 <TD colspan=2>
	   <?php echo _("Auteur"); ?>&nbsp;:
	   <INPUT TYPE="text" NAME="liv_auteur" size=15" <?php if ($auteur = $dao->getFilter('auteur')) echo 'value="'.$auteur.'"'; ?> >
    </TD>
  </tr>
  <tr>
    <TD>
	   <?php echo _("ISBN"); ?>&nbsp;:
	   <INPUT TYPE="text" NAME="liv_ISBN" size=15" <?php if ($isbn = $dao->getFilter('ISBN')) echo 'value="'.$isbn.'"'; ?> >
    </TD>
	 <TD>
	   <?php echo _("Edition"); ?>&nbsp;:
	   <INPUT TYPE="text" NAME="liv_ed" size=15" <?php if ($edition = $dao->getFilter('edition')) echo 'value="'.$edition.'"'; ?> >
    </TD>
    <TD>
	   <?php echo _("Collection"); ?>&nbsp;:
	   <INPUT TYPE="text" NAME="liv_col" size=15" <?php if ($collection = $dao->getFilter('collection')) echo 'value="'.$collection.'"'; ?> >
    </TD>
    <TD>
    <input type="checkbox" name="liv_prete" value="1"
    <?php 
    	if ($dao->getIncludeLoaned()) 
			echo ' checked="yes" />'; 
    	else
			echo ' />';
    	echo " : "._("Pr&ecirc;t&eacute;");	
    ?> 
    </TD>
  </TR>
  <TR>
    <TD>
    <?php echo _("Genre"); ?>&nbsp;:
	<select NAME = "liv_genre">
        <option VALUE=""
        <?php
          if (!$dao->getFilter('genre_ID'))
            echo ' selected="selected"';
	      echo ">"._("[non sp&eacute;cifi&eacute;]");
          echo '</option>';
          if ($genres) {
			foreach ($genres as $id => $value) {
				echo '<option VALUE="'.$id.'"';
				if ($dao->getFilter('genre_ID') == $id)
				    echo ' selected="selected"';
				echo '>'.$value.'</option>';
            }
          }
        ?>
      </select>
    </TD>
    <TD>
	<?php echo _("Etat"); ?>&nbsp;:
	<select NAME = "liv_etat">
        <option VALUE=""
        <?php
        if (!$dao->getFilter('etat_ID'))
          echo ' selected="selected"';
		echo ">"._("[non sp&eacute;cifi&eacute;]");
        echo '</option>';

		if ($etats != false) {
			foreach ($etats as $etat_id => $etat_l ) {
				echo '<option VALUE="'.$etat_id.'"';
				if ($dao->getFilter('etat_ID') == $etat_id)
					echo ' selected="selected"';
				echo '>'.$etat_l.'</option>';
			}
		}
        ?>
      </select>
    </TD>
    <TD>
      <?php echo _("Location"); ?>&nbsp;:
	    <select NAME = "liv_location">
        <option VALUE=""
        <?php
        if (!$dao->getFilter('location_ID'))
          echo ' selected="selected"';
	    echo ">"._("[non sp&eacute;cifi&eacute;]");
        echo '</option>';
        
        if ($locations) {
          foreach ($locations as $id => $value) {
            echo '<option VALUE="'.$id.'"';
            if ($dao->getFilter('location_ID') == $id)
                echo ' selected="selected"';
            echo '>'.$value.'</option>';
          }
        }
        ?>
      </select>
    </TD>
    <TD>
    <input type="checkbox" name="liv_pas_prete" value="1"
    <?php 
    	if ($dao->getIncludeNotLoaned()) 
    		echo ' checked="yes" />'; 
    	else
    		echo ' />';
    	echo " : "._("Non pr&ecirc;t&eacute;");	
    ?> 
    </TD>
  </TR>
  <TR>
	  <TD COLSPAN=2>
	    <?php echo _("Mots Clefs"); ?>&nbsp;:
		<INPUT TYPE="text" NAME="liv_motclefs" size=35" <?php if ($motclefs = $dao->getFilter('motclefs')) echo 'value="'.$motclefs.'"'; ?> >
    </TD>
	  <TD COLSPAN=2>
	    <?php echo _("Resum&eacute;"); ?>&nbsp;:
	    <INPUT TYPE="text" NAME="liv_resume" size=35" <?php if ($resume = $dao->getFilter('resume')) echo 'value="'.$resume.'"'; ?>>
    </TD>
  </TR>
  <TR>
    <td colspan="4" align="center">
		<a href="javascript:submitform('search_form','');">
			<span id="searchbtn" ><?php echo _('Rechercher'); ?></span>
		</a>
	</td>
  </TR>
</TABLE>
</form>
 </CENTER><HR>

<?php   
    if (isset($_GET['start'])) 
		$rec_start = $_GET['start'];
    else 
		$rec_start = 0;
    $dao->setStartRow($rec_start);
    $rec_bypage = get_max_record();
    $dao->setRowsPerPage($rec_bypage);
    if (!$dao->doSearch())
		print "PROBLEME : ".biblio_db_error()."<br>".$dao->getQuery(); 
	else {
		/*
		 * # of results found
		 */
		$total_rows = $dao->getFoundRowCount();
		echo "<CENTER>";                
		echo _("Nombre d'enregistrement(s) trouv&eacute;(s) : ").$total_rows;
		echo "<br/><br/>\n";
		
		/*
		 *  Table header
		 */
		$allowedCols = SearchDAO::getAllowedCols();
		if (isset($_SESSION['login']))
			$login = $_SESSION['login'];
		else
			$login = "";
		$col_cfg = new ColCfgDAO($_SESSION["login"], "search");
		$cols = $col_cfg->getConfig();
        if ($sort_order == DBSortOrder::desc)
			$img = '<img src="images/arrow_down.gif"/>';
        else
			$img = '<img src="images/arrow_up.gif"/>';
				
		echo "<TABLE class=\"search_results\">\n<TR>";
		foreach ($cols as $col) {
			if (!SearchDAO::isAllowedCol($col->db_name))
				continue;
			echo '<th><a href="javascript:submitform(\'search_form\', \''.$col->db_name.'\')">';
			echo $allowedCols[$col->db_name];
			if ($sort_col == $col->db_name)
				echo $img;
			echo '</a></th>';
		}

		if (isset($_SESSION['login']) && (!empty($_SESSION['login']))) 
			echo "<TH>"._("Action")."</TH>";
		echo "</tr>";
        
		/*
		 * Results
		 */
		$i=0;
		while ($row = $dao->getRow()) {      
            $liv_id = $row['id'];           
            $liv_local_ID =  $row['location_ID'];                                
            
			/*
			 * Replace location ID by location name
			 */
            if (isset($locations[$liv_local_ID]))
            	$row['location_ID'] = $locations[$liv_local_ID];
            else
            	$row['location_ID'] = '???';
            	
            $i++;
            // Check if book is already borrowed            
			if (isset($row['emprunteur'])) {
				$style = "borrowed";
			}
			else {
				if ($i%2 == 1)
					$style = "odd";
				else 
					$style = "even";
			}						
            echo "\n<TR class=\"$style\">";
			
			foreach ($cols as $col) {
				if (!SearchDAO::isAllowedCol($col->db_name))
					continue;
				$link = "JavaScript:newPopup('resume.php?id=".$liv_id."');";
				echo '<TD><A href="'.$link.'">'.$row[$col->db_name].'</A></TD>';
			}
			
            if (!empty($login)) {
				echo '<TD align="center">';
				echo "<A HREF=\"JavaScript:newPopup('admin.php?user=".$login."&action=mod&type=livre&id=".$liv_id."');\">";
				echo '<img src="images/b_edit.png" alt="'._("Editer").'" title="'._("Editer").'"></A>';
				echo "&nbsp;<A HREF=\"JavaScript:newPopup('admin.php?user=".$login."&action=del&type=livre&id=".$liv_id."');\">";
				echo '<img src="images/b_delete.png" alt="'._("Effacer").'" title="'._("Effacer").'"></A>';
				if (!isset($row['emprunteur'])) {
					echo "&nbsp;<A HREF=\"JavaScript:newPopup('pret_out.php?id=".$liv_id."');\">";
					echo '<img src="images/book_out.png" alt="'._("Pr&ecirc;ter").'" title="'._("Pr&ecirc;ter").'"></A>';
				}
				else {
					echo "&nbsp;<A HREF=\"JavaScript:newPopup('pret_in.php?id=".$liv_id."');\">";
					echo '<img src="images/book_in.png" alt="'._("Retour").'" ';
					echo 'title="'._("Retour (Pr&ecirc;t&eacute; &agrave; ").$row['emprunteur'].')"></A>';
				}
				echo '</TD>';
			}
		}
		echo "</TABLE><br>";
        
		if ($rec_bypage > 0) {
			$last_page = ceil($total_rows / $rec_bypage);
			$cur_page = $rec_start / $rec_bypage;

			echo "<a href=\"search.php?start=0\"><img src=\"images/b_firstpage.png\"></a>&nbsp;";
			$start = max($cur_page - 10, 0);
			$stop  = min($cur_page + 10, $last_page);
			for ($j=$start; $j < $stop; $j++) {
				$todisp=($j * $rec_bypage);
				echo "&nbsp;";
				if ($todisp==$rec_start) 
					echo "&gt;";
				echo "<a href=\"search.php?start=$todisp\">";
				echo $j + 1;
				echo "</a>";
				if ($todisp==$rec_start)
					echo "&lt;";
			}
			$last = ($last_page - 1) * $rec_bypage;
			echo "&nbsp;<a href=\"search.php?start=$last\"><img src=\"images/b_lastpage.png\"></a>";
		}
		echo "</CENTER>";
	} 
	$dao->saveToSession();

?>
<br/><br/>
<div>
	<span id=left-text>
		<A HREF="index.php"><?php echo _("retour menu principal"); ?></A>
	</span>
</div>

<?php if ($total_rows > 0) { ?>
<div>
	<span id=right-text>
		<A HREF="search.php?export=csv"><?php echo _("Exporter ce r&eacute;sultat"); ?></A>
	</span>
</div>

<br/>
<?php
}
include("includes/footer.inc");
?>
